﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XWord.Fundamental.Domain.Model;
using Luna.NHibernate;
using uNhAddIns.Adapters;

namespace XWord.Fundamental.Domain.Impl
{
    [PersistenceConversational(MethodsIncludeMode = MethodsIncludeMode.Implicit)]
    public class EtymaLibraryModel : IEtymaLibraryModel
    {
        private readonly IRepository<EtymaLibrary> _etymaLibraryRepository;

        public EtymaLibraryModel(IRepository<EtymaLibrary> etymaLibraryRepository)
        {
            _etymaLibraryRepository = etymaLibraryRepository;
        }

        public IList<EtymaLibrary> LoadEtymaLibraryList()
        {
            return _etymaLibraryRepository.GetAll();
        }

        public IList<EtymaLibrary> SearchEtymaLibraryList(string text)
        {
            return _etymaLibraryRepository.GetAll();
        }

        [PersistenceConversation(ConversationEndMode = EndMode.CommitAndContinue)]
        public void Save(EtymaLibrary entity)
        {
            _etymaLibraryRepository.MakePersistent(entity);
        }

        [PersistenceConversation(ConversationEndMode = EndMode.CommitAndContinue)]
        public void Delete(EtymaLibrary entity)
        {
            _etymaLibraryRepository.MakeTransient(entity);
        }

        private static IList<EtymaMessage> ParseText(string text)
        {
            var etymas = text.Split(new char[] { ',' });
            IList<EtymaMessage> messageList = new List<EtymaMessage>();
            for (int i = 0; i < etymas.Length; i++)
            {
                var message = new EtymaMessage(etymas[i].Trim());
                if (!string.IsNullOrEmpty(message.Name))
                {
                    messageList.Add(message);
                }
            }
            return messageList;
        }

        private List<EtymaMessage> _etymaMessageList;

        private void GetEtymaMessage()
        {
            if (_etymaMessageList == null)
            {
                _etymaMessageList = new List<EtymaMessage>();
                var list = LoadEtymaLibraryList();
                foreach (var item in list)
                {
                    _etymaMessageList.AddRange(ParseText(item.Name));
                }
            }
        }

        public IList<EtymaMessage> GetPreFix()
        {
            GetEtymaMessage();
            return _etymaMessageList.Where(e => (e.EtymaType & EtymaType.PreFix) == EtymaType.PreFix).ToList();
        }

        public IList<EtymaMessage> GetSuffix()
        {
            GetEtymaMessage();
            return _etymaMessageList.Where(e => (e.EtymaType & EtymaType.Suffix) == EtymaType.Suffix).ToList();
        }
    }
}
